package masterlink.sarPoint.process;

import java.util.Arrays;

import masterlink.sarPoint.Start;
import masterlink.sarPoint.util.MyQueue;
import masterlink.sarPoint.util.NumUtil;
import masterlink.sarPoint.vo.Ipush;
import masterlink.sarPoint.vo.MKLine;
import masterlink.sarPoint.vo.FitxTick;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class Worker extends Thread{
	private static final Logger log=LoggerFactory.getLogger(Worker.class);
	private static final String p="|";
	private static int cnt=0;
	private static double mt[] = new double[Start.runEMA.size()];
    private static int sar0=0;//SAR的方向,在上方或在下方
    private static int sarCnt=0;
    private static float sarAF=0.02f;
    private static float sarValue=0.0f;
    private static int sarMax = Start.runSAR.get(2);
    private static int sarPnt=0;
    private static MyQueue<Integer> queueH=new MyQueue<Integer>(20);
    private static MyQueue<Integer> queueL=new MyQueue<Integer>(20);
    private static MyQueue<String> queueData=new MyQueue<String>(20);
    private static NumUtil nu = new NumUtil();

	@Override
	public void run() {
		log.info("Worker start");
//		setPnt();
		while(true){
			try{
				doWorker((Ipush)Start.poll());
			}catch(Exception e){}
		}
	}

	private void doWorkerM(Ipush obj){
		int ttime,price,qty,sumqty;
		ttime = obj.gettTime();
		price = obj.getPrice();
		qty = obj.getQty();
		sumqty = obj.getSumqty();

		if(Start.setTickM(ttime,price,qty,sumqty,Start.KLine)){
			log.debug("=================================={}, {}",Start.curPnt,ttime);
		}
	}
	private void doWorker(Ipush obj){
		int ttime,price,qty,sumqty;
		ttime = obj.gettTime();
		price = obj.getPrice();
		qty = obj.getQty();
		sumqty = obj.getSumqty();
		if(Start.setTick(ttime,price,qty,sumqty)){
			log.debug("=================================={}, {}",Start.curPnt,ttime);
			tLine2hLine();
			genSta(ttime,price);
		}
	}
	/**
	 * 今日K線寫入歷史K線中,供指標計算用 
	 */
	private void tLine2hLine(){
		int cnt = Start.curPnt + 1;
		if(cnt % Start.KLine == 1 && cnt != 1){
			MKLine ml = new MKLine();
			//把1分k線資料放進去,1分k線放入到KLine裡面來,產生完以後,加入到歷史n分K去
			for(int i=Start.KLine;i>0;i--){
				FitxTick ft = Start.td.get(cnt-i);
				ml.setCtime(ft.getCtime());
				ml.setoPrice(ft.getoPrice());
				ml.sethPrice(ft.gethPrice());
				ml.setlPrice(ft.getlPrice());
				ml.setcPrice(ft.getcPrice());
				ml.setPrice(ft.getQtyPrice());
				ml.setQty(ft.getsQty());
//				log.trace("data:{}",ml.toString());
			}
			Start.lmk.add(ml);
			log.trace("data:{}",ml.toString());
		}
	}
	/**
	 * 指標進行計算
	 * @param ttime
	 */
	private void genSta(int ttime,int price){
		//計算P*Q /Q
		compPoint0();
		//計算SAR
		compPoint1();
		String str[] = new String[3];
		for(String a:queueData){
			if(a.indexOf("30|")>=0){
				str[0]=a.substring(3);
			}else if(a.indexOf("60|")>=0){
				str[1]=a.substring(3);
			}else{
				str[2]=a;
			}
//			log.info("queueData:{}",a);
			queueData.poll();
		}
		masterlink.sarPoint.util.NumUtil.formatNumber(Double.parseDouble(str[0]));
		String ss = p+nu.formatNumber(Double.parseDouble(str[0]))+p+nu.formatNumber(Double.parseDouble(str[1]))+
				p+str[2]+p+price/1000+p;
		log.trace(Arrays.toString(str)+"|"+price);
//		Start.iPush.submitSubject(Start.ipushParam.get(7)+".0000602", ss.getBytes(), 0, ss.getBytes().length);
//		FitxTick ft = Start.td.get(Start.curPnt-1);
//		log.info("ttime:"+ttime+p+ft.getoPrice()+p+ft.gethPrice()+p+ft.getlPrice()+p+ft.getcPrice()+p+ft.getsQty()+p+ft.getQtyPrice());
	}
	/**
	 * 計算SAR指標
	 */
	private void compPoint1(){
		//計算SAR
        for(MKLine mk:Start.lmk){
            queueH.add(mk.gethPrice());
            queueL.add(mk.getlPrice());
            switch(sar0){
                case 0://sar的狀態尚未開始
                    if(mk.getcPrice()>queueH.peek()){//漲勢買進
                        sar0=1;
                    }
                    if(mk.getcPrice()<queueL.peek()){//跌勢賣出
                        sar0=2;
                    }
                    break;
                case 1://sar:漲勢買進
                    switch(sarCnt){
                        case 0:
                            sarPnt=mk.getcPrice();
                            sarValue=queueL.min();
                            sarCnt=1;
                            break;
                        default:
                            if(sarPnt<mk.getcPrice()){
                                sarPnt = mk.getcPrice();
                                sarCnt=sarCnt+1;
                            }
                            if(sarCnt>sarMax){
                            	sarCnt=sarMax;
                            }
                            sarValue=sarValue+((sarAF*(float)sarCnt)*(queueH.max()-sarValue));
                            if(sarValue>mk.getcPrice()){
                                sarPnt = mk.getcPrice();
                                sarCnt=1;
                                sar0=2;
                                sarValue=queueH.max();
                                queueL.clear();
                                queueH.add(mk.gethPrice());
                                queueL.add(mk.getlPrice());
                            }
                            break;
                    }
                    break;
                case 2://sar:跌勢賣出
                    switch(sarCnt){
                        case 0:
                            sarPnt=mk.getcPrice();
                            sarValue=queueH.max();
                            sarCnt=1;
                            break;
                        default:
                            if(sarPnt>mk.getcPrice()){
                                sarPnt = mk.getcPrice();
                                sarCnt=sarCnt+1;
                            }
                            if(sarCnt>sarMax){
                            	sarCnt=sarMax;
                            }
                            sarValue=sarValue-((sarAF*(float)sarCnt)*(sarValue-queueL.min()));
                            if(sarValue<mk.getcPrice()){
                                sarPnt = mk.getcPrice();
                                sarCnt=1;
                                sar0=1;
                                sarValue=queueL.min();
                                queueH.clear();
                                queueH.add(mk.gethPrice());
                                queueL.add(mk.getlPrice());
                            }
                            break;
                    }
                    break;
            }
//            log.trace(mk.toString()+", sar0:"+sar0+", sarCnt:"+sarAF*(float)sarCnt+", sarPnt:"+sarPnt+", sarValue:"+sarValue);
//            log.trace("hPrice:{}, lPrice:{}",queueH.max(),queueL.min());
        }
//        log.trace("sar:{}, sarValue:{}",sar0,sarValue);
        queueData.add(sar0+"|"+sarValue);
	}
	/**
	 * 計算 P*Q / Q
	 */
	private void compPoint0(){
		int size = Start.lmk.size();
		//計算P*Q /Q
		for(int a:Start.runEMA){
			if(a > size){
				continue;
			}
			int qty1=0;
			long price1=0;
			double avgprice=0.0;
			try{
				for(int i=1;i<=a;i++){
					MKLine mkl = Start.lmk.get(Start.lmk.size()-i);
					qty1=qty1+mkl.getQty();
					price1 = price1 + mkl.getPrice();
					avgprice = avgprice + (double)price1 / (double)qty1;
				}
				mt[Start.runEMA.indexOf(a)] = (double)price1/(double)qty1;
//				log.trace("{}EMA = {}",a,(double)price1/(double)qty1);
				queueData.add(a+"|"+((double)price1/(double)qty1));
			}catch(Exception e){
				log.error("error:{}",e);
			}
		}
	}
}
